package chloroform

import javax.servlet._
import http.{HttpServletResponse, HttpServletRequest}

/**
 * Created by IntelliJ IDEA.
 * User: zslajchrt
 * Date: 17.3.11
 * Time: 15:31
 * To change this template use File | Settings | File Templates.
 */

class RequestCache extends Filter {

  def init(config: FilterConfig) = null

  def doFilter(req: ServletRequest, resp: ServletResponse, chain: FilterChain) = {
    try {
      RequestCache.requestTL.set(req.asInstanceOf[HttpServletRequest])
      RequestCache.responseTL.set(resp.asInstanceOf[HttpServletResponse])
      chain.doFilter(req, resp)
    }
    finally {
      RequestCache.requestTL.remove
      RequestCache.responseTL.remove
    }
  }

  def destroy = null

}

object RequestCache {
  private val requestTL = new ThreadLocal[HttpServletRequest]
  private val responseTL = new ThreadLocal[HttpServletResponse]

  def getRequest(): HttpServletRequest = {
    val servletRequest: HttpServletRequest = requestTL.get
    if (servletRequest == null) {
      throw new IllegalStateException("RequestCache does not contain any request for the current thread. Is the RequestCache filter installed?")
    } else servletRequest
  }

  def getResponse(): HttpServletResponse = {
    val servletResponse: HttpServletResponse = responseTL.get
    if (servletResponse == null) {
      throw new IllegalStateException("RequestCache does not contain any response for the current thread. Is the RequestCache filter installed?")
    } else servletResponse
  }

  def apply(): HttpServletRequest = getRequest
}
